<template>
  <!-- 金钱输入框 -->
  <el-input v-model="showMoney" @focus="onMoneyFocus" @blur="onMoneyBlur">
    <template #prepend v-if="slots.prepend">
      <slot name="prepend"></slot>
    </template>
    <template #append v-if="slots.append">
      <slot name="append"></slot>
    </template>
    <template #suffix v-if="slots.suffix">
      <slot name="suffix"></slot>
    </template>
    <template #prefix v-if="slots.prefix">
      <slot name="prefix"></slot>
    </template>
  </el-input>
</template>
<script setup>
import { ref, computed, onMounted, useSlots, watch } from "vue";
import { thousands, translateNumber } from "@/utils/index";
import { ElMessage } from "element-plus";
const emits = defineEmits(["update:modelValue"]);
const slots = useSlots();
const props = defineProps({
  modelValue: {
    type: [String, Number],
    default: "",
  },
});

const showMoney = ref("");

watch(
  () => props.modelValue,
  (newVal) => {
    if (newVal) {
      showMoney.value = thousands(newVal);
    } else {
      showMoney.value = "";
    }
  }
);

onMounted(() => {
  if (props.modelValue) {
    showMoney.value = thousands(props.modelValue);
  }
});
const onMoneyFocus = () => {
  if (showMoney.value) {
    showMoney.value = translateNumber(showMoney.value);
  }
};
const onMoneyBlur = () => {
  if (showMoney.value) {
    if (isNaN(showMoney.value * 1)) {
      emits("update:modelValue", "");
      showMoney.value = "";
      ElMessage.warning("金额请输入数字");
      return;
    }
    if (String(showMoney.value) !== String(props.modelValue)) {
      emits("update:modelValue", showMoney.value);
    }
  }
};
</script>